﻿Imports SS
Imports SS.Databases
Imports SS.Databases.Connecter
Imports SS.ApplicationBlock
Imports System.IO

Public Class ExternalBoundaryIVR

	Private sbMessage As New System.Text.StringBuilder()
	Public Property Message As String
		Get
			Return sbMessage.ToString()
		End Get
		Private Set(ByVal value As String)
			sbMessage.AppendLine(value)
			RaiseEvent MessageChanged(sbMessage.ToString())
		End Set
	End Property

	Public Event MessageChanged(ByVal message As String)

	Private mExitCode As Integer = -1
	Public ReadOnly Property ExitCode As Integer
		Get
			Return mExitCode
		End Get
	End Property

	Private Sub WriteSciprtFTP_IVR(ByVal fileName As String)

		Dim myReader As StreamReader
		Try
			myReader = New StreamReader(ApplicationBlock.Config.GetAppConfig("TemplateScript"), System.Text.UnicodeEncoding.UTF8)
		Catch ex As Exception
			Throw New Exception("ไม่พบไฟล์ต้นแบบสำหรับสร้าง Script FTP", ex)
		End Try

		Dim strMessage As String = myReader.ReadToEnd()
		myReader.Close()
		myReader.Dispose()

		If File.Exists(ApplicationBlock.Config.GetAppConfig("DestinationScript") & "script_ivr.txt") Then
			Try
				File.Delete(ApplicationBlock.Config.GetAppConfig("DestinationScript") & "script_ivr.txt")
			Catch ex As Exception
				Throw New Exception("ไม่สามารถลบไฟล์ Script FTP ได้", ex)
			End Try
		End If

		My.Computer.FileSystem.WriteAllText(ApplicationBlock.Config.GetAppConfig("DestinationScript") & "script_ivr.txt", strMessage.Replace("{filename}", fileName), True)
	End Sub

	Private Function ProcessBatchFile() As Integer
		'Create a variable to hold the value you wish
		'to return to your calling method
		Dim batchSuccessful As Integer
		'Create a new Process(), I just happen
		'to name this "YourName"
		Dim batchExecute As New Process()

		'This is a method that you can use to set
		'properties for your new Process()
		Dim batchExecuteInfo As New ProcessStartInfo()

		'Tell the program to not use the built-in Shell provided
		'with the OS, wew ant to start it ourselved
		batchExecuteInfo.UseShellExecute = False

		'Tell the process to not open a Console window
		batchExecuteInfo.CreateNoWindow = False	'True

		batchExecuteInfo.FileName = ApplicationBlock.Config.GetAppConfig("PathBatchFile")

		'Set your process info here
		batchExecute.StartInfo = batchExecuteInfo

		'Start your Process(), this will start the
		'command line and send your command
		'Process.Start(batchExecuteInfo)
		batchExecute.Start()

		'Set the period of time to wait for the associated
		'process to exit, and blocks the current thread
		'until the time has elapsed or the
		'process has exited
		batchExecute.WaitForExit(Convert.ToInt32(ApplicationBlock.Config.GetAppConfig("DelayWaitFTP")))

		'Create a variable and assign it the value
		'of your processes exit code
		Dim intExit As Integer = batchExecute.ExitCode

		'Check if the process has completed
		'and return a status of 0 (succeeded). If not
		'then we want to kill the process
		If intExit > 0 And Not batchExecute.HasExited Then
			'Here you can assign a value to a variable
			'to return to your calling method
			batchSuccessful = 1
			batchExecute.Kill()
		Else
			'Do something here and
			'assign your successful variable a 0
			batchSuccessful = 0
		End If
		'Return the value (1 or 0) to
		'your calling method
		Return batchSuccessful
	End Function

	Private Sub BackupFile(ByVal fileName As String)
		Dim strBackupPath As String = ApplicationBlock.Config.GetAppConfig("BackupFilePath") & "\"
		Dim desFile As String = fileName
		Dim prefix As String = String.Empty
		Dim i As Integer = 0

		Do While File.Exists(strBackupPath & prefix & desFile)
			i += 1
			prefix = i.ToString & "_"
		Loop

		My.Computer.FileSystem.MoveFile(ApplicationBlock.Config.GetAppConfig("Path") & "\" & fileName, strBackupPath & prefix & desFile)
	End Sub

	Private Sub DestroyFile(ByVal fileName As String)
		Try
			File.Delete(ApplicationBlock.Config.GetAppConfig("Path") & "\" & fileName)
		Catch ex As Exception
			Throw New Exception("ไม่สามารถลบไฟล์หลังจากทำการ import ได้", ex)
		End Try
	End Sub

	Public Function ImportIVR() As Boolean
		Dim strPath As String = ApplicationBlock.Config.GetAppConfig("Path") & "\"
		Dim myReader As StreamReader
		Dim CurrentLine As String
		Dim strValue() As String


		Dim dl As DL.IVRFile = Nothing
		'Dim fileName As String = ApplicationBlock.Config.GetAppConfig("FileName").Replace("yyyymmdd", runDate.ToString("yyyyMMdd"))

		'writ script for FTP
		'WriteSciprtFTP_SBM(fileName)

		'call batch
		Try
			ProcessBatchFile()
		Catch ex As Exception
			Throw New Exception("ไม่สามารถ FTP ไฟล์ได้", ex)
		End Try

		Dim strSourceFile() As String = System.IO.Directory.GetFiles(strPath, "*.txt")

		If strSourceFile.Length <= 0 Then
			Throw New Exception("ไม่พบไฟล์ที่ได้จากการ FTP")
		End If

		For Each fileName As String In strSourceFile
			Dim iItems As Integer = 0
			Dim fInfo As New System.IO.FileInfo(fileName)
			fileName = fInfo.Name

			If dl Is Nothing Then
				dl = New DL.IVRFile
			End If

			dl.UpdateFlage("I", fileName)

			Try
				myReader = New StreamReader(strPath & fileName, System.Text.UnicodeEncoding.UTF8)
			Catch ex As Exception
				dl.Rollback()
				LogToDB(fileName, iItems, "F")
				Throw ex
			End Try

			While myReader.Peek <> -1
				CurrentLine = myReader.ReadLine
				strValue = CurrentLine.Split("|")
				If Not strValue(0).ToUpper.Equals("T") Then
					Dim IVR As New Entity.IVRFileItem
					With IVR
						.ivrftp_id = 0
						.ivr_create_dt = strValue(0)
						.ivr_msisdn = strValue(1)
						.ivr_profile = strValue(2)
						.ivr_package_id = strValue(3)
						.ivr_package_start = strValue(4)
						.ivr_package_end = strValue(5)
						.ivr_function = strValue(6)
						.ivr_status = strValue(7)
						.ivr_resp_code = strValue(8)
						.ivr_desc = strValue(9)
						.ivr_validate_id = strValue(10)
						.ivr_resigter_id = strValue(11)
						.ivr_cp_transaction_id = strValue(12)
						.ivr_ref_transaction_id = strValue(13)
						.ivr_in_transaction_id = strValue(14)
						.ivr_channel = strValue(15)
						.ivr_channel_reference = strValue(16)
						.ivr_file_name = fileName
						.record_status = "A"
						.create_user_id = "BATCHJOB"
						.create_date = Now
						.upd_user_id = "BATCHJOB"
						.upd_date = Now
					End With

					Try
						dl.Insert(IVR)
						iItems += 1	'count items
					Catch ex As Exception
						myReader.Close()
						myReader = Nothing
						dl.Rollback()
						LogToDB(fileName, iItems, "F")
						Throw ex
					End Try

				End If

			End While

			myReader.Close()
			myReader = Nothing

			Try
				BackupFile(fileName) 'backup file
			Catch ex As Exception
				dl.Rollback()
				LogToDB(fileName, iItems, "F")
				Throw ex
			End Try

			Try
				DestroyFile(fileName) 'delete file ที่ download
			Catch ex As Exception
				dl.Rollback()
				LogToDB(fileName, iItems, "F")
				Throw ex
			End Try

			LogToDB(fileName, iItems, "T")
		Next

		If dl IsNot Nothing Then
			dl.Commit()
		End If


		Return True
	End Function

	Private Sub LogToDB(ByVal fileName As String, ByVal item As String, ByVal result As String)
		Try
			DL.IVRFile.InsertLog(fileName, item, result)
		Catch ex As Exception
			Common.LogError.AddLogException(ex)
		End Try
	End Sub

End Class
